import argparse
from copy import copy
import logging
from pathlib import Path
from pyexpat import model
import shutil
import multiprocessing
import subprocess
import pprint
from shutil import copyfile


def dense_recon(cmd_path,image_dir,models_path,output_dir,sfm_dir,type='colmap'):
    if type == 'colmap':
        # print(models_path)
        # print(output_dir)
        output_dir.mkdir(exist_ok=True)
        cmd = [
            str(cmd_path), 'image_undistorter',
            '--image_path', str(image_dir),
            '--input_path', str(models_path),
            '--output_path', str(output_dir),
            '--output_type','COLMAP',
            '--max_image_size','2000']
        subprocess.run(cmd,check=True)
        cmd = [
            str(cmd_path), 'patch_match_stereo',
            '--workspace_path', str(output_dir),
            '--workspace_format','COLMAP',
            '--PatchMatchStereo.geom_consistency', 'true',]
        subprocess.run(cmd,check=True)
        cmd = [
            str(cmd_path), 'stereo_fusion',
            '--workspace_path', str(output_dir),
            '--workspace_format','COLMAP',
            '--input_type','geometric',
            '--output_path', str(output_dir/'fused.ply')]
        subprocess.run(cmd,check=True)
    elif type =='openmvs':
        output_dir.mkdir(exist_ok=True)
        cmd = [
            'colmap', 'image_undistorter',
            '--image_path', str(image_dir),
            '--input_path', str(models_path),
            '--output_path', str(output_dir),
            '--output_type','COLMAP',
            '--max_image_size','2000']
        subprocess.run(cmd,check=True)
        cmd=['colmap', 'model_converter',
        '--input_path',str(output_dir/'sparse'),
        '--output_path',str(sfm_dir/'sparse'),
        '--output_type','TXT']
        subprocess.run(cmd,check=True)
        imgs=sfm_dir/'images'
        if imgs.exists() is not True:
            imgs.mkdir()
            for images in image_dir.iterdir():
                copyfile(str(images),str(imgs/images.name))
        model_colmap=sfm_dir/'model_colmap.mvs'
        outputfile=sfm_dir/'model_dense.ply'
        print(sfm_dir)
        cmd=[str(cmd_path/'InterfaceCOLMAP'),'--working-folder',str(sfm_dir.resolve()),'--input-file',str(sfm_dir.resolve()),'--output-file',str(model_colmap.resolve())]
        subprocess.run(cmd,check=True)
        cmd=[str(cmd_path/'DensifyPointCloud'),'--input-file',str(model_colmap.resolve()),'--working-folder',str(sfm_dir.resolve()),'--output-file',str(outputfile.resolve())]
        subprocess.run(cmd,check=True)